// 地区级联相关接口（省/市/区/镇）
import request from '../utils/request.ts'

export interface RegionItem { code: string; name: string }

//normalize的作用是将一个数组中的对象转换为RegionItem类型的数组
const normalize = (list: any[]): RegionItem[] => {
  if (!Array.isArray(list)) return []
  return list
    .map((x: any) => {
      if (typeof x === 'string') {
        return { code: x, name: x }
      }
      return {
        code: String(x.code ?? x.value ?? x.id ?? ''),
        name: String(x.name ?? x.label ?? x.text ?? '')
      }
    })
    .filter((x) => x.code && x.name)
}
//获取省份
export const getProvincesService = async () => {
  const res: any = await request.get('/districts/provinces')
  return normalize(res?.data ?? res?.list ?? res)
}
//获取市
export const getCitiesService = async (provinceName: string) => {
  const res: any = await request.get(`/districts/cities?provinceName=${encodeURIComponent(provinceName)}`)
  return normalize(res?.data ?? res?.list ?? res)
}
//获取区
export const getDistrictsService = async (cityName: string, provinceName: string) => {
  const res: any = await request.get(`/districts/districts?provinceName=${encodeURIComponent(provinceName)}&cityName=${encodeURIComponent(cityName)}`)
  return normalize(res?.data ?? res?.list ?? res)
}



